package com.example.cms.DB;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static final String URL_WITHOUT_DB = "jdbc:mysql://localhost:3306?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String URL = "jdbc:mysql://localhost:3306/hospital_system?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "20040815";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("加载MySQL驱动失败", e);
        }
    }

    /**
     * 获取数据库连接（不带数据库名）
     */
    public static Connection getConnectionWithoutDB() throws SQLException {
        return DriverManager.getConnection(URL_WITHOUT_DB, USERNAME, PASSWORD);
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    /**
     * 关闭数据库资源
     */
    public static void closeResources(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            System.err.println("关闭数据库资源时发生错误: " + e.getMessage());
        }
    }

    /**
     * 关闭连接和语句
     */
    public static void closeResources(Connection conn, Statement stmt) {
        closeResources(conn, stmt, null);
    }

    /**
     * 测试数据库连接
     */
    public static boolean testConnection() {
        try (Connection conn = getConnection()) {
            return true;
        } catch (SQLException e) {
            System.err.println("数据库连接测试失败: " + e.getMessage());
            return false;
        }
    }
}